"""
文章管理API路由
"""
from fastapi import APIRouter, Depends, HTTPException, Query, BackgroundTasks
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional
from app.database import get_async_db
from app.schemas.article import (
    ArticleGenerateRequest, ArticleResponse, ArticleListResponse,
    ArticleGenerationResult, ArticleStatus
)
from app.services.article_service import article_service
from app.utils.exceptions import (
    ArticleNotFoundError, ThemeNotFoundError, DatabaseError,
    ContentGenerationError, ImageGenerationError
)
from app.utils.logger import logger

router = APIRouter(prefix="/articles", tags=["文章管理"])


@router.post("/generate", response_model=ArticleGenerationResult, summary="生成文章")
async def generate_article(
    request: ArticleGenerateRequest,
    background_tasks: BackgroundTasks,
    db: AsyncSession = Depends(get_async_db)
):
    """
    根据主题生成文章
    
    - **theme_id**: 主题ID（必填）
    - **include_images**: 是否生成图片（默认true）
    - **num_content_images**: 内容配图数量（0-10张，默认3张）
    
    生成过程包括：
    1. 调用DeepSeek生成标题、摘要、正文
    2. 调用通义万相生成封面和配图
    3. 上传图片到微信公众号
    4. 保存文章到数据库
    """
    try:
        result = await article_service.generate_article(db, request)
        
        if result.success:
            logger.info(f"文章生成成功: {result.article.title if result.article else 'Unknown'}")
        else:
            logger.warning(f"文章生成失败: {result.message}")
        
        return result
    
    except ThemeNotFoundError:
        raise HTTPException(status_code=404, detail="主题不存在")
    
    except ContentGenerationError as e:
        logger.error(f"内容生成错误: {str(e)}")
        raise HTTPException(status_code=422, detail=f"内容生成失败: {str(e)}")
    
    except ImageGenerationError as e:
        logger.error(f"图像生成错误: {str(e)}")
        raise HTTPException(status_code=422, detail=f"图像生成失败: {str(e)}")
    
    except DatabaseError as e:
        logger.error(f"生成文章数据库错误: {str(e)}")
        raise HTTPException(status_code=500, detail="生成文章失败")
    
    except Exception as e:
        logger.error(f"生成文章未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.get("/", response_model=ArticleListResponse, summary="获取文章列表")
async def get_articles(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(20, ge=1, le=100, description="返回的记录数"),
    theme_id: Optional[str] = Query(None, description="主题ID筛选"),
    status: Optional[ArticleStatus] = Query(None, description="状态筛选"),
    db: AsyncSession = Depends(get_async_db)
):
    """
    获取文章列表，支持分页和筛选
    
    - **skip**: 跳过的记录数（用于分页）
    - **limit**: 返回的记录数（最大100）
    - **theme_id**: 按主题ID筛选
    - **status**: 按状态筛选（draft/published/failed）
    """
    try:
        return await article_service.get_articles(db, skip, limit, theme_id, status)
    
    except DatabaseError as e:
        logger.error(f"获取文章列表数据库错误: {str(e)}")
        raise HTTPException(status_code=500, detail="获取文章列表失败")
    
    except Exception as e:
        logger.error(f"获取文章列表未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.get("/{article_id}", response_model=ArticleResponse, summary="获取文章详情")
async def get_article(
    article_id: str,
    db: AsyncSession = Depends(get_async_db)
):
    """
    根据ID获取文章详情
    
    - **article_id**: 文章ID
    """
    try:
        article = await article_service.get_article_by_id(db, article_id)
        return ArticleResponse.from_orm(article)
    
    except ArticleNotFoundError:
        raise HTTPException(status_code=404, detail="文章不存在")
    
    except DatabaseError as e:
        logger.error(f"获取文章详情数据库错误: {str(e)}")
        raise HTTPException(status_code=500, detail="获取文章详情失败")
    
    except Exception as e:
        logger.error(f"获取文章详情未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.delete("/{article_id}", summary="删除文章")
async def delete_article(
    article_id: str,
    db: AsyncSession = Depends(get_async_db)
):
    """
    删除文章
    
    - **article_id**: 文章ID
    
    注意：如果文章已发布到微信草稿箱，会同时尝试删除草稿
    """
    try:
        success = await article_service.delete_article(db, article_id)
        return {"success": success, "message": "文章删除成功"}
    
    except ArticleNotFoundError:
        raise HTTPException(status_code=404, detail="文章不存在")
    
    except DatabaseError as e:
        logger.error(f"删除文章数据库错误: {str(e)}")
        raise HTTPException(status_code=500, detail="删除文章失败")
    
    except Exception as e:
        logger.error(f"删除文章未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.put("/{article_id}/status", response_model=ArticleResponse, summary="更新文章状态")
async def update_article_status(
    article_id: str,
    status: ArticleStatus,
    draft_id: Optional[str] = None,
    db: AsyncSession = Depends(get_async_db)
):
    """
    更新文章状态
    
    - **article_id**: 文章ID
    - **status**: 新状态（draft/published/failed）
    - **draft_id**: 草稿ID（可选）
    """
    try:
        article = await article_service.update_article_status(db, article_id, status, draft_id)
        return ArticleResponse.from_orm(article)
    
    except ArticleNotFoundError:
        raise HTTPException(status_code=404, detail="文章不存在")
    
    except DatabaseError as e:
        logger.error(f"更新文章状态数据库错误: {str(e)}")
        raise HTTPException(status_code=500, detail="更新文章状态失败")
    
    except Exception as e:
        logger.error(f"更新文章状态未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.get("/theme/{theme_id}", response_model=ArticleListResponse, summary="获取主题下的文章")
async def get_articles_by_theme(
    theme_id: str,
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(20, ge=1, le=100, description="返回的记录数"),
    db: AsyncSession = Depends(get_async_db)
):
    """
    获取指定主题下的所有文章
    
    - **theme_id**: 主题ID
    - **skip**: 跳过的记录数
    - **limit**: 返回的记录数
    """
    try:
        return await article_service.get_articles(db, skip, limit, theme_id=theme_id)
    
    except DatabaseError as e:
        logger.error(f"获取主题文章数据库错误: {str(e)}")
        raise HTTPException(status_code=500, detail="获取主题文章失败")
    
    except Exception as e:
        logger.error(f"获取主题文章未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.post("/batch/generate", summary="批量生成文章")
async def batch_generate_articles(
    theme_ids: List[str],
    include_images: bool = True,
    num_content_images: int = 3,
    background_tasks: BackgroundTasks = BackgroundTasks(),
    db: AsyncSession = Depends(get_async_db)
):
    """
    批量生成文章
    
    - **theme_ids**: 主题ID列表
    - **include_images**: 是否生成图片
    - **num_content_images**: 每篇文章的配图数量
    
    注意：批量生成会在后台进行，避免请求超时
    """
    async def batch_generate():
        results = []
        for theme_id in theme_ids:
            try:
                request = ArticleGenerateRequest(
                    theme_id=theme_id,
                    include_images=include_images,
                    num_content_images=num_content_images
                )
                result = await article_service.generate_article(db, request)
                results.append({
                    "theme_id": theme_id,
                    "success": result.success,
                    "message": result.message,
                    "article_id": result.article.id if result.article else None
                })
            except Exception as e:
                results.append({
                    "theme_id": theme_id,
                    "success": False,
                    "message": str(e),
                    "article_id": None
                })
                logger.error(f"批量生成文章失败 {theme_id}: {str(e)}")
        
        logger.info(f"批量生成文章完成，总数: {len(theme_ids)}")
    
    background_tasks.add_task(batch_generate)
    
    return {
        "message": f"已开始批量生成 {len(theme_ids)} 篇文章",
        "theme_count": len(theme_ids)
    }